package com.lzh.async.thread;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @author zhehen.lu
 * @date 2025/8/13 19:50
 */
public class RequestContextAwareRunnable implements Runnable {
    private Runnable task;
    private RequestAttributes context;

    public RequestContextAwareRunnable(Runnable task, RequestAttributes context) {
        this.task = task;
        this.context = context;
    }

    @Override
    public void run() {
        if (this.context != null) {
            RequestContextHolder.setRequestAttributes(this.context);
        }

        try {
            this.task.run();
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }

    }
}
